<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }

  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }

  .rj-cell.max span {
    font-size: 16px;
    padding-right: 20px;
  }

  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }

  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }

  .rj-cell.note label {
    float: left;
  }

  .rj-cell.note span {
    width: 80%;
    display: inline-block;
  }

  .weui-cells {
    margin-top: 0;
  }

  .weui-cells_form {
    background: #fbfbfb;
  }

  .weui-cell {
    background: #fff;
  }

  .weui-cells__title {
    text-align: left;
  }

  .oitem {
    padding: 3px;
  }

  .hide {
    display: none;
  }

  #acts {
    font-size: 0;
  }

  #acts span {
    font-size: 14px;
  }

  .halfbtn {
    display: inline-block;
    width: 49%;
  }

  .weui-label {
    text-align: left;
  }

  .time {
    border: none;
    font-size: 17px;
  }

  .weui-cell_select {
    padding: 10px 15px;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }


  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }

  .weui_uploader_files {
    list-style: none;
  }

  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }

  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }

  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }

  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }

  .weui_uploader_bd {
    overflow: hidden;
  }
  .outstore >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }

  .weui-cell.fir {
    border-top: 0;
  }
  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }

  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }

  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }

  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
  }

  li.weui-uploader_file {
    display: inline-block;
    padding: 3px 5px;
  }

  ul#images {
    text-align: right;
  }
</style>
<template>
  <div class="addsell" style="overflow: hidden;">
    <div
      style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      录入销售订单
      <a href="javascript:;" @click="$router.push({name: 'Sellform'})" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px"/>
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form method="post" id="formid">
        <input type="hidden" name="entity.deliProvince" v-model="currStroom.province"/>
        <input type="hidden" name="entity.deliCity" v-model="currStroom.city"/>
        <input type="hidden" name="entity.deliDistrict" v-model="currStroom.area"/>
<!--        <input type="hidden" name="entity.arriProvince" v-model="currCustomer.province"/>-->
<!--        <input type="hidden" name="entity.arriCity" v-model="currCustomer.city"/>-->
<!--        <input type="hidden" name="entity.arriDistrict" v-model="currCustomer.district"/>-->
        <input type="hidden" name="entity.arriProvince"/>
        <input type="hidden" name="entity.arriCity"/>
        <input type="hidden" name="entity.arriDistrict"/>
        <input type="hidden" name="entity.type" :value="currCustomer.flag == 3 ? 2 : 1"/>
        <!--        <input type="hidden" name="entity.salestype" :value="defSaletype.value" />-->
        <!--        <input type="hidden" name="entity.faretype" :value="defFaretype.value" />-->
        <input type="hidden" name="entity.sorgguid" v-model="currDepart.orgguid"/>
        <input type="hidden" name="entity.porgname" v-model="currDepart.orgname"/>
        <input type="hidden" name="entity.partitionflag" value="1"/>
        <!--        <input type="hidden" name="entity.flag" :value="flag" />-->
        <div class="cellgroup">
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label" ref="msgDiv" style="width: 66px;">申请人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input notnull" type="text" name="entity.applyname" readonly="true" v-model="username"
                     style="width: 25%;">
              <input type="hidden" name="entity.depname" ref="depname" v-model="currDepart.name"/>
              <select class="weui-select" name="depguid" v-model="departid" id="depart" style="width: 70%;padding-left: 5px;padding-right: 5px;">
                <option value="">请选择部门</option>
                <option selected="" v-for="(item, index) in departments" :key="item.guid" :value="item.guid">
                  {{item.name}}
                </option>
              </select>
            </div>
          </div>

          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">货品类型</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.quitSRType" v-model="quitsrtype">
                <option value="1">原料</option>
                <option value="2">成品</option>
                <option value="3">次品</option>
<!--                <option value="4">辅料</option>-->
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单类型</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.flag" v-model="flag">
                <option selected="" v-for="(item, index) in ordertypes" :key="item.dictValue" :value="item.dictValue">
                  {{item.dictLabel}}
                </option>
              </select>
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell fir">
            <div class="weui-cell__hd"><label class="weui-label">客户</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.customerguid" v-model="currCustomer.guid"/>
              <input type="hidden" name="entity.customername" ref="customername" v-model="currCustomer.name"/>
              <model-list-select :list="customers"
                                 v-model="customerid"
                                 option-value="guid"
                                 option-text="name"
                                 placeholder="请选择" style="border: 0;">
              </model-list-select>
<!--              <select class="weui-select" name="entity.customerguid" v-model="customerid" id="customer">-->
<!--                <option value="" disabled>请选择</option>-->
<!--                <option selected="" v-for="(item, index) in customers" :key="item.guid" :value="item.guid">-->
<!--                  {{item.name}}-->
<!--                </option>-->
<!--              </select>-->
              <!--              <input class="weui-input notnull" id="customername" type="text" :value="customername" name="entity.customername" placeholder="请选择客户">-->
            </div>
          </div>
          <div class="weui-cell" v-if="contracts.length > 0">
            <div class="weui-cell__hd"><label class="weui-label">销售合同</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" class="weui-input" v-model="contracts[0].guid" name="entity.contractid">
              <input type="hidden" class="weui-input" v-model="contracts[0].code" name="entity.contractcode">
              <input class="weui-input" type="text" v-model="contracts[0].name" name="entity.contractname" readonly>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">收货城市</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" id="endCity" name=""
                     placeholder="请选择收货城市">
            </div>
            <div class="weui-cell__ft" v-if="hasCustomer">
              <div class="weui-vcode-btn" @click="manageAddr"><i class="weui-icon-info-circle"></i></div>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">详细地址</label></div>
            <div class="weui-cell__bd">
<!--              <input class="weui-input" type="text" id="arriAddress" name="entity.arriAddress"-->
<!--                     v-model="currCustomer.address" placeholder="请输入收货详细地址">-->
              <input class="weui-input" type="text" id="arriAddress" name="entity.arriAddress" placeholder="请输入收货详细地址">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">收货联系人</label></div>
            <div class="weui-cell__bd">
<!--              <input class="weui-input" type="text" id="arriContact" name="entity.arriContact" v-model="currCustomer.contact" placeholder="请输入收货联系人">-->
              <input class="weui-input" type="text" id="arriContact" name="entity.arriContact" placeholder="请输入收货联系人">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">联系电话</label></div>
            <div class="weui-cell__bd">
<!--              <input class="weui-input" type="text" id="arriContactNo" name="entity.arriContactNo"-->
<!--                     v-model="currCustomer.contactno" placeholder="请输入收货人电话">-->
              <input class="weui-input" type="text" id="arriContactNo" name="entity.arriContactNo" placeholder="请输入收货人电话">
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell fir">
            <div class="weui-cell__hd">
              <label class="weui-label">发货日期</label>
            </div>
            <div class="weui-cell__bd">
              <input type="text" id='datetime-picker' class="time" name="" placeholder="请选择要求发货日期" autocomplete="off"/>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd">
              <label class="weui-label">到货日期</label>
            </div>
            <div class="weui-cell__bd">
              <input type="text" id='datetime-picker2' class="time" name="" placeholder="请选择要求到货日期"/>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">物流结算</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.faretype" v-model="faretypekey">
                <option value="" disabled>请选择</option>
                <option selected="" v-for="(item, index) in faretypes" :key="item.dictkey" :value="item.dictkey">
                  {{item.dicttext}}
                </option>
              </select>
              <!--              <input class="weui-input" type="text" id="faretype" name="entity.faretype" :value="defFaretype.title" placeholder="请选择物流结算方式">-->
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">配送方式</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.deliverytype" v-model="deliverytype">
                <option value="" disabled>请选择</option>
                <option v-for="(item, index) in deliverytypes" :value="item.dictkey">{{item.dicttext}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="cellgroup">
          <div class="weui-cell weui-cell_select fir">
            <div class="weui-cell__hd"><label class="weui-label">计价方式</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.settletype" v-model="settletype">
                <option value="" disabled>请选择</option>
                <!--                <option selected="" v-for="(item, index) in settletypes" :key="item.dictkey" :value="item.dictkey" v-show="deliverytype != 2 || deliverytype==2 && item.dictkey!=1">{{item.dicttext}}</option>-->
                <option selected="" v-for="(item, index) in settletypes" :key="item.dictkey" :value="item.dictkey">
                  {{item.dicttext}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell" v-if="settletype == 1 && benifitordeduct == 1 && (benefittype == 1 || benefittype == 2 && contracts.length == 0)">
            <div class="weui-cell__hd"><label class="weui-label">赠送(%)</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.concession" readonly v-model="discount">
            </div>
          </div>
          <div class="weui-cell" v-if="settletype == 1 && benifitordeduct == 1 && (benefittype == 2 && contracts.length != 0)">
            <div class="weui-cell__hd"><label class="weui-label">赠送(%)</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.concession" readonly v-model="contracts[0].maxdiscount">
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">结算币种</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.currency" v-model="currency">
                <option value="" disabled>请选择</option>
                <option selected="" v-for="(item, index) in currencys" :key="item.dictkey" :value="item.dictkey">
                  {{item.dicttext}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">付款方式</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.paytype" v-model="paytype">
                <option value="" disabled>请选择</option>
                <!--                <option selected="" v-for="(item, index) in paytypes" :key="item.dictkey" :value="item.dictkey" v-show="deliverytype != 2 || deliverytype==2 && item.dictkey!=1">{{item.dicttext}}</option>-->
                <option selected="" v-for="(item, index) in paytypes" :key="item.dictkey" :value="item.dictkey">
                  {{item.dicttext}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell weui-cell_select" v-if="paytype == 3">
            <div class="weui-cell__hd"><label class="weui-label">结算账期</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.settlebilling" v-model="settlebilling">
                <option value="" disabled>请选择</option>
                <option selected="" v-for="(item, index) in settlebillings" :value="item.dictkey">{{item.dicttext}}
                </option>
              </select>
            </div>
          </div>
          <div class="weui-cell" v-if="settlebilling == 2">
            <div class="weui-cell__hd"><label class="weui-label">收到发票后结算天数</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="number" name="entity.settledays" placeholder="请输入收到发票后结算天数">
            </div>
          </div>
          <div class="weui-cell weui-cell_select" v-if="currCustomer.flag == 3">
            <div class="weui-cell__hd"><label class="weui-label">运输方式</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select" name="entity.transType" v-model="transType">
                <option v-for="(item, index) in transTypes" :value="item.dictkey">{{item.dicttext}}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="weui-cell fir">
          <div class="weui-cell__hd"><label class="weui-label">附件上传</label></div>
          <!--          <div class="weui-cell__bd">-->
          <!--            <input class="weui-input" type="number" name="entity.lbweight" v-model="lbweight">-->
          <!--          </div>-->
          <div class="weui-cell__ft">
            <div class="weui_uploader_bd">
              <ul class="weui_uploader_files"></ul>
              <div class="weui_uploader_input_wrp inrow">
                <UploadFile class="weui_uploader_input" v-on:pushfile="setFile"></UploadFile>
              </div>
            </div>
          </div>
          <ul class="weui-uploader_files" id="images">
            <!--                  <li class="weui-uploader_file" v-for="(img, index) in filenames" :id="img"  @click=del(img,1) ><img :src="images1.srcStr[index]" width="85" /></li>-->
            <li class="weui-uploader_file" v-for="(fil, index) in filenames" @click=delFile(fil,fileids[index])>
              {{fil}}
            </li>
          </ul>
        </div>
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="entity.remarks" placeholder="请输备注内容" rows="2"></textarea>
            </div>
          </div>
        </div>

        <SellformItem v-for="(item, index) in oitems" :key="index" :itemNo="item" :isLast="index+1 == oitems.length"
                      :products="products" :departid="departid" :contract="contracts.length != 0 ? contracts[0] : ''"
                      :specs="saleSpec" :quitsrtype="quitsrtype" :settletype="settletype" :paytype="paytype"
                      :benifitordeduct="benifitordeduct" :benefittype="benefittype" :discount="discount"
                      :prodpricestra="prodpricestra" :currency="currency" :orgid="currDepart.orgguid" @doAddItem="addItem(index + 1)"
                      @doDelItem="delItem" @doBigorder="toBigorder"></SellformItem>

        <div class="weui-btn-area">
          <!--          <a class="weui-btn weui-btn_primary halfbtn" href="javascript:" @click="postForm(1)">保存</a>-->
          <a class="weui-btn weui-btn_primary subbtn" href="javascript:" @click="postForm(2)">提交</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import SellformItem from "./SellformItem";
  import UploadFile from "../common/UploadFile";
  import qs from 'qs';
  import 'vue-search-select/dist/VueSearchSelect.css'
  import {ModelListSelect} from 'vue-search-select'

  export default {
    name: 'AddSellform',
    data() {
      return {
        openid: localStorage.openid,//'oIuV2v77MaLCAQILhjI6h6oTWpHI',
        username: localStorage.username,
        customers: [],
        currCustomer: '',
        customerid: '',
        departments: [],
        currDepart: '',
        departid: '',
        defaultDep: {},
        fpricetypes: [], //运费计价方式（按车、按吨）
        fpricetype: 1,
        salestypes: [],
        defSaletype: {},
        faretypes: [], //物流结算方式（公司结算、客户结算）
        faretypekey: 1,
        // farepricetypes: [],
        // farepricetype: '',
        defFaretype: {},
        customerguid: '',
        customername: '',
        rcamount: '',
        storeCitys: {},
        storeAddrs: {},
        storeRnames: {},
        storeTels: {},
        customerCitys: {},
        customerAddrs: {},
        customerRnames: {},
        customerTels: {},
        itemRemarks: {},
        cusrcamounts: {},
        products: [],
        saleSpec: [],
        oitems: [0],
        contracts: [],
        quitsrtype: 2,
        storerooms: [],
        currStroom: '',
        storermid: '',
        settletypes: [],
        settletype: 1,
        paytypes: [], //付款方式（全额预付、上车付款、到货付款）
        paytype: '',
        flag: 1,
        deliverytypes: [],
        deliverytype: 2,
        benifitordeduct: '',
        benefittype: '',
        discount: '',
        currencys: [], //结算币种
        currency: 1,
        settlebillings: [], //结算账期
        settlebilling: 1,
        prodpricestra: 2,  //为1获取不到价格不许提交，2.允许手动录入,
        senddate: '',
        arrivedate: '',
        filenames: [],
        fileids: [],
        contractParam: '',
        ordertypes: [],
        transTypes: '',
        transType: 1,
        liftTypes: '',
        transClauses: '',
        arriPorts: '',
        arriPort: '',
        seaWinds: '',
        seaWind: '',
        seaTemp: '',
        seaTemperatures: '',
        artoken: '',
        packCity: '',
        hooks: []
      }
    },
    components: {SellformItem, UploadFile, ModelListSelect},
    computed: {
      hasCustomer: function () {
        return this.customerid != '' ? true : false;
      }
    },
    created() {
      window.addEventListener('setItem', () => {
        this.openid = localStorage.getItem('openid');
        this.username = localStorage.getItem('username');
      })
    },
    mounted() {

      let that = this;
      //日历初始化
      $("#datetime-picker").calendar();
      $("#datetime-picker2").calendar();

      $("#datetime-picker").change(function () {
        that.senddate = $(this).val().replace(/\//g, '-');
      })
      $("#datetime-picker2").change(function () {
        that.arrivedate = $(this).val().replace(/\//g, '-');
      })

      //地址初始化
      $("#startCity").cityPicker();
      $("#endCity").cityPicker();
      $("#startCity").change(function () {
        let addr = $(this).val().split(' ');
        $('input[name="entity.deliProvince"]').val(addr[0]);
        $('input[name="entity.deliCity"]').val(addr[1]);
        $('input[name="entity.deliDistrict"]').val(addr[2]);
      })
      $("#endCity").change(function () {
        console.log('$("#endCity").change')
        let addr = $(this).val().split(' ');
        $('input[name="entity.arriProvince"]').val(addr[0]);
        $('input[name="entity.arriCity"]').val(addr[1]);
        $('input[name="entity.arriDistrict"]').val(addr[2]);
      })

      //获取select下拉数据
      //this.getCustomer();
      this.getDiscountType();
      this.getDepartment();
      this.getStorms();
      // this.getProductinfo();
      //this.getSalesspec();
      this.getFpricetype(); //运费计价方式
      this.getSalestype();
      this.getOrdertype();
      this.getFaretype();
      this.getSettletypes();
      this.getDeliverytypes();
      this.getCurrencys();
      this.getSettlebillings();
      this.getPaytypes();
      this.getTranstypes();
      this.getLifttypes();
      this.getTransClauses();
      this.getArriPorts();
      this.getSeaTemps();
      this.getSeaWinds();
      this.getHooks();
      //this.getFarepricetypes();

      //根据userid和时间戳生成唯一字符串
      this.artoken = this.createToken();
      //
      // //从state中获取数据并赋值
      // if (this.$store.state.arriAddr.address != '') {
      //   this.getStateAddr();
      // } else {
      //   this.setCustomer();
      // }
    },
    activated() {
      this.artoken = this.createToken();
      //从state中获取数据并赋值
      if (this.$store.state.arriAddr.address != '') {
        this.getStateAddr();
      } else {
        this.setCustomer();
      }
    },
    watch: {
      'departid': function (data) {
        // this.$refs.depname.value = $('#depart').find('option:selected').text();
        this.currDepart = this.departments.filter(function (item) {
          return item.guid == data;
        })[0] || '';
        this.getCustomer(data);
        // this.getProductinfo();
      },
      'customerid': function (data) {
        // this.$refs.customername.value = $('#customer').find('option:selected').text();
        this.currCustomer = this.customers.filter(function (item) {
          return item.guid == data;
        })[0] || '';
        this.currency = this.currCustomer.currency != '' ? this.currCustomer.currency : 1;
        this.$store.commit('setCustomer', this.currCustomer);
        this.getContract();
        //电商订单
        if (this.currCustomer.flag == 1) {
          this.flag = 4;
        } else {
          this.flag = 1;
        }
        if (this.currCustomer != '') {
          this.currCustomer.flag == 3 ? this.transType = 2 : '';
        }
      },
      'storermid': function (data) {
        this.currStroom = this.storerooms.filter(function (item) {
          return item.guid == data;
        })[0] || '';
      },
      'quitsrtype': function (val) {
        this.getDiscountType();

        if (val == 2) {
          this.fpricetype = 1;
          this.settletype = 1;
          // this.paytype = 1;
          this.deliverytype = 2;
        } else if (val == 1 || val == 3) {
          this.fpricetype = 2;
          this.settletype = 2;
          // this.paytype = 2;
          this.deliverytype = 1;
        }
      },
      'deliverytype': function (val) {
        this.faretypekey = val == 1 ? 2 : 1;
        // this.paytype = val == 1 ? 2 : 1;
      },
      // 'currFpricetype': function (data) {
      //   this.defFpricetype = data[1];
      // },
      // 'salestypes': function (data) {
      //   this.defSaletype = data[0];
      // },
      // 'faretypes': function (data) {
      //   this.defFaretype = data[0];
      // }
      arriPort: function (val) {
        let that = this;
        if (val != undefined) {
          this.$refs.arriCountry.value = val.country;
        }
        if (val.guid == 999) {
          that.addPort();
        }
      },
      currCustomer: function (currCustomer) {
        if (currCustomer.province) {
          $('#endCity').val(currCustomer.province + ' ' + currCustomer.city + ' ' + currCustomer.district);
          $('input[name="entity.arriProvince"]').val(currCustomer.province);
          $('input[name="entity.arriCity"]').val(currCustomer.city);
          $('input[name="entity.arriDistrict"]').val(currCustomer.district);
        }

        $('#arriAddress').val(currCustomer.address);
        $('#arriContact').val(currCustomer.contact);
        $('#arriContactNo').val(currCustomer.contactno);
        // this.packCity = currCustomer.province + ' ' + currCustomer.city + ' ' + currCustomer.district;
      }
    },
    methods: {
      addPort: function() {
        let that = this;
        let addHtml = '<div class="cellgroup"> <div class="weui-cell"> <div class="weui-cell__hd"><label class="weui-label" style="width: 70px;text-align: left;">港口名称</label></div> <div class="weui-cell__bd"> <input class="weui-input" type="text" name="name" placeholder="请输入名称"> </div> </div> <div class="weui-cell"> <div class="weui-cell__hd"><label class="weui-label" style="width: 70px;text-align: left;">所属国家</label></div> <div class="weui-cell__bd"> <input class="weui-input" type="text" name="country" placeholder="请输入国家"> </div> </div> </div>';
        $.modal({
          title: '添加港口',
          text: addHtml,
          buttons: [
            { text: "确定", onClick: function(){
                if ($('input[name="name"]').val() == '') {
                  that.toastText('请输入港口名称');
                  return;
                }
                if ($('input[name="country"]').val() == '') {
                  that.toastText('请输入所属国家');
                  return;
                }
                let name = $('input[name="name"]').val();
                let country = $('input[name="country"]').val();
                that.axios({
                  method: 'post',
                  url: '/sales/Port!addOrupdate.action',
                  params: {name: name, country: country, type: 2}
                }).then(response => {
                  if (response.data.msg == "success") {
                    that.getArriPorts(name);
                  } else if (response.data.isrepeat == "true") {
                    that.toastText('该港口已存在');
                  } else {
                    this.toastText('添加港口失败');
                  }
                });
              }},
            { text: "取消", className: "default", onClick: function(){
               that.arriPort = '';
              }},
          ]
        });
      },
      delFile: function (name, id) {
        let that = this;
        $.confirm('确定要删除？', function () {
          that.axios({
            method: 'post',
            url: '/sales/Fileinfo!delete.action',
            params: {fileid: id}
          })
          that.fileids = that.fileids.filter(item => {
            return item != id;
          })
          that.filenames = that.filenames.filter(item => {
            return item != name;
          })
        })
      },
      setFile: function (file) {
        this.filenames.push(file.name);
        this.fileids.push(file.id);
        console.log('filenames：', this.filenames)
      },
      addItem: function (index) {
        this.oitems.push(index);
      },
      delItem: function () {
        this.oitems.pop();
      },
      toBigorder: function () {
        let that = this;
        $.confirm("按大订单流程处理?", function () {
          that.flag = 2;
        });
      },
      setCustomer: function () {
        this.currCustomer = this.$store.state.customer;
      },
      manageAddr: function () {
        this.$router.push({name: 'AddressList'});
        return false;
      },
      getStateAddr: function () {
        let addr = this.$store.state.arriAddr;

        $('input[name="entity.arriProvince"]').val(addr.province);
        $('input[name="entity.arriCity"]').val(addr.city);
        $('input[name="entity.arriDistrict"]').val(addr.district);
        // this.packCity = addr.province + ' ' + addr.city + ' ' + addr.district;
        $('#endCity').val(addr.province + ' ' + addr.city + ' ' + addr.district);
        $('#arriAddress').val(addr.address);
        $('#arriContact').val(addr.contact);
        $('#arriContactNo').val(addr.contactno);
      },
      //客户
      filterCustomer: function (item) {
        let sname = item.name;
        this.customerCitys[sname] = item.province + ' ' + item.city + ' ' + item.district;
        this.customerAddrs[sname] = item.address;
        this.customerRnames[sname] = item.contact;
        this.customerTels[sname] = item.contactno;
        this.cusrcamounts[sname] = item.rcamount != '' ? item.rcamount : 0;
        return {title: item.name, value: item.guid};
      },
      getCustomer: function (departid) {
        let that = this
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Customer!getCustomers.action',
          params: {departid: departid, functiontype: 13}
        }).then(response => {
          if (response.data.msg == "success") {
            that.customers = response.data.customers;
            that.customerid = that.customers[0].guid;
          } else {
            this.toastText('获取客户数据失败');
          }
        });
      },
      getContract: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Salecontract!getContract.action',
          params: {customerid: this.customerid, orgguid: this.currDepart.orgguid, status: 1}
          // params: {customerid: '120ED2C35C7D462ABE3F9E095B1E0F4F', orgguid: '0A9BB9B7213C4ECAA6B2C9C2ADD5AF13', status: 1}
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.contracts = data.msg;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取销售合同数据失败');
          }
        });
      },
      getDiscountType: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!getDiscountType.action',
          params: {type: this.quitsrtype}
        }).then(response => {
          let data = response.data;
          if (data.code == 1) {
            this.benifitordeduct = data.msg.benifitordeduct;
            this.benefittype = data.msg.benefittype;
            this.discount = data.msg.discount;
            this.prodpricestra = data.msg.prodpricestra;
            this.contractParam  = data.msg.contractParam ;
          } else if (data.code == 0) {
            this.toastText(data.msg);
          } else {
            this.toastText('获取赠送数据失败');
          }
        });
      },
      //部门
      filterDepartment: function (item) {
        return {title: item.name, value: item.guid};
      },
      getDepartment: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDepartment.action',
          params: {sPermission: 2}
        }).then(response => {
          if (response.data.status == "true") {
            //that.departments = response.data.result.map(that.filterDepartment);
            that.departments = response.data.result;
            this.departid = response.data.result[0].guid;
          } else if (response.data.status == "false") {
            this.toastText(response.data.result);
          }  else {
            this.toastText('获取部门数据失败');
          }
        });
      },
      //运费计价方式
      filterFpricetype: function (item) {
        return {title: item.dicttext, value: item.dictkey};
      },
      getFpricetype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 94}
        }).then(response => {
          if (response.statusText == "OK") {
            that.fpricetypes = response.data;
            that.fpricetype == response.data[0].dictkey;
            // that.fpricetypes = response.data.map(that.filterFpricetype);
            // $('#farepricetype').select({
            //   title: "选择计价方式",
            //   items: that.fpricetypes,
            //   onChange: function (data) {
            //     $('input[name="entity.farepricetype"]').val($('#farepricetype').data('values'));
            //   }
            // });
          } else {
            this.toastText('获取运费计价方式数据失败');
          }
        });
      },
      //销售形式
      getSalestype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 13}
        }).then(response => {
          if (response.statusText == "OK") {
            that.salestypes = response.data.map(that.filterFpricetype);
            $('#salestype').select({
              title: "选择销售形式",
              items: that.salestypes,
              onChange: function (data) {
                $('input[name="entity.salestype"]').val($('#salestype').data('values'));
              }
            });
          } else {
            this.toastText('获取销售形式数据失败');
          }
        });
      },
      //是否挂机
      getHooks: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 122}
        }).then(response => {
          if (response.statusText == "OK") {
            that.hooks = response.data;
          } else {
            this.toastText('获取是否挂机数据失败');
          }
        });
      },
      //物流结算
      getFaretype: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 19}
        }).then(response => {
          if (response.statusText == "OK") {
            that.faretypes = response.data;
            this.faretypekey = response.data[0].dictkey;
            // that.faretypes = response.data.map(that.filterFpricetype);
            // $('#faretype').select({
            //   title: "选择物流结算方式",
            //   items: that.faretypes,
            //   onChange: function (data) {
            //     $('input[name="entity.faretype"]').val($('#faretype').data('values'));
            //   }
            // });
          } else {
            this.toastText('获取物流结算方式数据失败');
          }
        });
      },
      //订单类型
      getOrdertype: function () {
        let that = this;
        this.axios({
          method: 'get',
          url: '/prod-api/system/dict/data/type/sellform_flag',
        }).then(response => {
          if (response.data.code == 200) {
            that.ordertypes = response.data.data.filter(item => item.dictValue != 4);
          } else {
            this.toastText('获取订单类型数据失败');
          }
        });
      },
      getSettletypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 93}
        }).then(response => {
          if (response.statusText == "OK") {
            that.settletypes = response.data;
            this.settletype = response.data[0].dictkey;
          } else {
            this.toastText('获取结算方式数据失败');
          }
        });
      },
      getDeliverytypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 48}
        }).then(response => {
          if (response.statusText == "OK") {
            that.deliverytypes = response.data;
          } else {
            this.toastText('获取物流配送方式数据失败');
          }
        });
      },
      //获取物流运输方式（汽运、海运、空运）
      getTranstypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 116}
        }).then(response => {
          if (response.statusText == "OK") {
            that.transTypes = response.data;
          } else {
            this.toastText('获取物流运输方式数据失败');
          }
        });
      },
      //获取海运提单类型（正本、电放）
      getLifttypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 118}
        }).then(response => {
          if (response.statusText == "OK") {
            that.liftTypes = response.data;
          } else {
            this.toastText('获取海运提单类型数据失败');
          }
        });
      },
      getArriPorts: function (name = '') {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Port!listNopage.action',
        }).then(response => {
          if (response.data.msg == "success") {
            that.arriPorts = response.data.ports.filter(item => {
              return item.type == 2;
            }).concat({guid: 999, name: '添加港口'});
            if (name != '') {
              that.arriPort = that.arriPorts.filter(item => {
                return item.name == name;
              })[0];
            }
          } else {
            this.toastText('获取海运港口数据失败');
          }
        });
      },
      getSeaTemps: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 120}
        }).then(response => {
          if (response.statusText == "OK") {
            that.seaTemperatures = response.data;
          } else {
            this.toastText('获取海运温度数据失败');
          }
        });
      },
      getSeaWinds: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 121}
        }).then(response => {
          if (response.statusText == "OK") {
            that.seaWinds = response.data;
          } else {
            this.toastText('获取海运通风数据失败');
          }
        });
      },
      //获取海运贸易条款
      getTransClauses: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 117}
        }).then(response => {
          if (response.statusText == "OK") {
            that.transClauses = response.data;
          } else {
            this.toastText('获取海运贸易条款数据失败');
          }
        });
      },
      getCurrencys: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 92}
        }).then(response => {
          if (response.statusText == "OK") {
            that.currencys = response.data;
            that.currency = response.data[0].dictkey;
          } else {
            this.toastText('获取结算币种数据失败');
          }
        });
      },
      getSettlebillings: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 46}
        }).then(response => {
          if (response.statusText == "OK") {
            that.settlebillings = response.data;
            that.settlebilling = response.data[0].dictkey;
          } else {
            this.toastText('获取结算账期数据失败');
          }
        });
      },
      getPaytypes: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 45}
        }).then(response => {
          if (response.statusText == "OK") {
            that.paytypes = response.data.filter(item => item.dictkey != 5);
            // that.paytype = response.data[0].dictkey;
          } else {
            this.toastText('获取付款方式数据失败');
          }
        });
      },
      //库房
      filterStorms: function (item) {
        let sname = item.name;
        this.storeCitys[sname] = item.province + ' ' + item.city + ' ' + item.area;
        this.storeAddrs[sname] = item.address;
        this.storeRnames[sname] = item.contact;
        this.storeTels[sname] = item.contacttel;
        return {title: item.name, value: item.guid};
      },
      getStorms: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findStorms.action'
        }).then(response => {
          if (response.data.status == "true") {
            this.storerooms = response.data.result;
          } else {
            $.toast('获取库房数据失败', 'text')
          }
        });
      },
      //品种
      filterProductinfo: function (item) {
        return {title: item.productname, value: item.guid};
      },
      //规格
      filterSalesspec: function (item) {
        let sname = item.name;
        this.itemRemarks[sname] = item.description;
        return {title: item.name, value: item.guid};
      },
      getSalesspec: function () {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findSalesspecification.action'
        }).then(response => {
          if (response.data.status == "true") {

            that.saleSpec = response.data.result;
          } else {
            $.toast('获取规格数据失败', 'text')
          }
        });
      },
      //提交表单数据
      postForm: function (type) {
        let that = this;

        if (this.flag != 2 && this.customerid == '') {
          $.alert('请选择客户！');
          return false;
        } else if ($('input[name="entity.faretype"]').val() == '') {
          $.alert('请选择物流结算！');
          return false;
        } else if (this.senddate == '') {
          $.alert('要求发货日期不能为空！');
          return false;
        } else if (this.arrivedate == '') {
          $.alert('要求到货日期不能为空！');
          return false;
        } else if (!this.paytype) {
          $.alert('请选择付款方式！');
          return false;
        } else if (!this.checkEmy('product')) {
          $.alert('品种不能为空！');
          return false;
        } else if (!this.checkEmy('specif')) {
          $.alert('请选择货品规格！');
          return false;
        } else if ((this.paytype == 1 || this.paytype == 2 || this.paytype == 3) && !this.checkEmy('price')) {
          $.alert('货品单价不能为空！');
          return false;
        } else if ((this.paytype == 4 || this.paytype == 5 || this.paytype == 6) && !this.checkEmy2('price')) {
          $.alert('货品单价不能为空！');
          return false;
        } else if (this.settletype == 1 && !this.checkEmy('orderpack')) {
          $.alert('请输入货品件数！');
          return false;
        } else if (this.settletype == 2 && !this.checkEmy('weight')) {
          $.alert('请输入货品重量！');
          return false;
        } else if (this.paytype != 4 && this.paytype != 5 && this.contractParam == 2 && this.contracts == 0) {
          $.alert('销售合同不能为空！')
          return false;
        }
        // else if (this.currCustomer.flag == 3 && this.transType == 2 && this.seaTemp == '') {
        //   $.alert('请输入海运温度条件！');
        //   return false;
        // } else if (this.currCustomer.flag == 3 && this.transType == 2 && this.seaWind == '') {
        //   $.alert('请输入海运通风情况！');
        //   return false;
        // } else if (this.currCustomer.flag == 3 && this.transType == 2 && (this.arriPort.name == '' || this.arriPort.name == undefined)) {
        //   $.alert('请选择目的港！');
        //   return false;
        // } else if (this.currCustomer.flag == 3 && this.transType == 2 && (this.$refs.arriCountry.value == '' || this.$refs.arriCountry.value == undefined)){
        //   $.alert('请输入目的港所属国家！');
        //   return false;
        // }

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData['entity.senddate'] = this.senddate;
        postData['entity.arrivedate'] = this.arrivedate;
        postData.fileids = this.fileids.join(',');

        this.axios({
          headers: {
            'artoken': this.artoken,
          },
          method: 'post',
          url: '/sales/Sellform!saveOrUpdate.action?opertype=' + type,
          data: qs.stringify(postData)
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            if (type == 1) {
              this.toastSuccess("保存成功");
            } else {
              this.toastSuccess("提交成功");
              location.href = '/vuecode/#/sellform/list';
              // this.$router.push({name: 'Sellform'});
            }
          } else {
            if (response.data.msg == 'repeatSubmit') {
              this.toastText('重复提交');
              this.artoken = this.createToken();
            } else if (response.data.msg == "outlogin") {
              this.toastText('请重新登录');
              this.artoken = this.createToken();
            } else if (response.data.msg == "canotopt") {
              this.toastText('不允许的操作');
              this.artoken = this.createToken();
            } else if (response.data.msg == "false") {
              this.toastText5(response.data.result);
              this.artoken = this.createToken();
            } else if (response.data.msg == "yz") {
              let result = response.data.result;
              let txt = '预收款余额不足</br>余额：' + result.prebalance + '</br>在途订单：' + result.ztbalance + '</br>可用余额：' + result.kybalance + '</br>当前订单：' + result.balance;
              this.toastText5(txt);
              this.artoken = this.createToken();
            } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
              //不不设置提示
              this.artoken = this.createToken();
            } else {
              this.toastError('系统错误');
              this.artoken = this.createToken();
            }
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i = 0; i < $('.oitem').not(':hidden').length; i++) {
          parr1.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
          parr2.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j = i + 1; j < parr2.length;) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0]) {
              parr2.splice(j, 1);//去除重复的对象；
            } else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      }
    }
  }
</script>
